/**********************************************************************\

 Copyright 2012 Diggory Blake

 This file is part of klip-engine

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

\**********************************************************************/

#include "ksprite.h"
#include "kerror.h"
#include "kengine.h"
#include "kanimation.h"
#include "kgraphics.h"
#include "kmaterial.h"

kSprite::kSprite(kEngine* engine) : kMesh2DBase(engine) {
	setMeshType(keMesh_TriangleFan);
	resize(4, 1, 1);
	setDiffuse(kColor(1.0f, 1.0f, 1.0f, 1.0f));
	setSize(1.0f, 1.0f);
	resetTextureCoords();
}
void kSprite::setFrame(int frame) {
	if (!getMaterial())
		return;

	const kImage* image = getMaterial()->getTexture();
	if (!image)
		return;

	float xf = getWidth()/(float)image->getSize().x;
	float yf = getHeight()/(float)image->getSize().y;
	int xn = (int)(1.0f/xf);
	int yn = (int)(1.0f/yf);
	int xi = frame % xn;
	int yi = frame / xn;

	setTextureCoord(0, kVec2(xi*xf, yi*yf));
	setTextureCoord(1, kVec2((xi+1)*xf, yi*yf));
	setTextureCoord(2, kVec2((xi+1)*xf, (yi+1)*yf));
	setTextureCoord(3, kVec2(xi*xf, (yi+1)*yf));
}
void kSprite::setSizeFromMaterial(const kVec2i& frames) {
	if (!getMaterial())
		return;

	const kImage* image = getMaterial()->getTexture();
	if (!image)
		return;

	setSize(kVec2(image->getSize()/frames));
}
kSprite::~kSprite() {
	if (getEngine()->getAnimation())
		getEngine()->getAnimation()->stop(this);
}
void kSprite::resetTextureCoords() {
	setTextureCoord(0, kVec2(0.0f, 0.0f));
	setTextureCoord(1, kVec2(1.0f, 0.0f));
	setTextureCoord(2, kVec2(1.0f, 1.0f));
	setTextureCoord(3, kVec2(0.0f, 1.0f));
}
